// dao/ShowtimeDAO.java
package main.java.com.cinema.dao;

import main.java.com.cinema.model.Showtime;

import java.io.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class ShowtimeDAO {
    private static final String SHOWTIME_FILE = "showtimes.dat";
    
    public List<Showtime> findAll() {
        List<Showtime> showtimes = new ArrayList<>();
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SHOWTIME_FILE))) {
            showtimes = (List<Showtime>) ois.readObject();
        } catch (FileNotFoundException e) {
            // 文件不存在，返回空列表
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return showtimes;
    }
    
    public Showtime findById(String showtimeId) {
        List<Showtime> showtimes = findAll();
        for (Showtime showtime : showtimes) {
            if (showtime.getId().equals(showtimeId)) {
                return showtime;
            }
        }
        return null;
    }
    
    public List<Showtime> findByDateRange(LocalDateTime start, LocalDateTime end) {
        List<Showtime> showtimes = findAll();
        List<Showtime> result = new ArrayList<>();
        
        for (Showtime showtime : showtimes) {
            LocalDateTime showtimeStart = showtime.getStartTime();
            if (!showtimeStart.isBefore(start) && !showtimeStart.isAfter(end)) {
                result.add(showtime);
            }
        }
        
        return result;
    }
    
    public boolean save(Showtime showtime) {
        List<Showtime> showtimes = findAll();
        showtimes.add(showtime);
        return saveAll(showtimes);
    }
    
    public boolean update(Showtime showtime) {
        List<Showtime> showtimes = findAll();
        for (int i = 0; i < showtimes.size(); i++) {
            if (showtimes.get(i).getId().equals(showtime.getId())) {
                showtimes.set(i, showtime);
                return saveAll(showtimes);
            }
        }
        return false;
    }
    
    public boolean delete(String showtimeId) {
        List<Showtime> showtimes = findAll();
        showtimes.removeIf(showtime -> showtime.getId().equals(showtimeId));
        return saveAll(showtimes);
    }
    
    private boolean saveAll(List<Showtime> showtimes) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SHOWTIME_FILE))) {
            oos.writeObject(showtimes);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
